package com.farewell.blog.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.farewell.blog.entity.QueryBean;
import com.farewell.blog.entity.SearchBlog;
import com.farewell.blog.pojo.Blog;
import com.farewell.blog.pojo.Type;
import com.farewell.blog.service.BlogService;
import com.farewell.blog.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

/**
 * @author Farewell
 * @date 2021/1/30
 */
@Controller
public class IndexController {

    @Autowired
    private BlogService blogService;

    @Autowired
    private TypeService typeService;

    @GetMapping(value = {"/", ""})
    public String index(Model model, @RequestParam(defaultValue = "1", value = "pageNum") Integer pageNum) {
        System.out.println("-----index--------");
        QueryBean queryBean = new QueryBean(pageNum, 10, null);
        Page<Blog> pageData1 = blogService.listBlog(queryBean);
        model.addAttribute("blogs", pageData1);
        queryBean.setCurrentPage(1);
        queryBean.setPageSize(20);
        Page<Type> pageData2 = typeService.listType(queryBean);
        model.addAttribute("types", pageData2);
        queryBean.setCurrentPage(1);
        queryBean.setPageSize(5);
        Page<Blog> pageData3 = blogService.listBlog(queryBean);
        model.addAttribute("recommends", pageData3);
        model.addAttribute("newblogs", pageData3.getRecords());
        return "index";
    }

    @PostMapping("/search")
    public String search(SearchBlog searchBlog, Model model, @RequestParam(defaultValue = "1", value = "pageNum") Integer pageNum) {
        QueryBean queryBean = new QueryBean(pageNum, 10, null);
        Page<Blog> pageData = blogService.getBlogsBySearch(queryBean, searchBlog);
        model.addAttribute("searchResult", pageData);
        return "search";
    }
}
